﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Rules;
using DiscoveryLogic.Analytics.UI.Common.Wizard;
using DiscoveryLogic.Common.Utilities;
using MessageBox=System.Windows.MessageBox;
using UserControl=System.Windows.Controls.UserControl;

namespace DiscoveryLogic.Analytics.Modules.LinkRules
{
    /// <summary>
    /// Interaction logic for LinkRuleSqlParameters.xaml
    /// </summary>
    public partial class LinkRuleSqlParameters : UserControl, IWizardPageBase 
    {
        private Wizard _Owner;

        public LinkRuleSqlParameters()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            EntityRelationRule rule =
                (EntityRelationRule) this._Owner.SharedVariables["LinkRule"];

            this.dvSqlParameterBindings.Rows.Clear();
            Regex paramRegex = new Regex(@"@([^\s,=\)]+)", RegexOptions.IgnoreCase);
            Match paramMatch = paramRegex.Match(rule.Sql);
            while (paramMatch.Success)
            {
                string paramName = paramMatch.Groups[1].Value;
                DataGridViewRow dr = new DataGridViewRow();

                DataGridViewTextBoxCell cellParamName = new DataGridViewTextBoxCell();
                cellParamName.Value = paramName;
                dr.Cells.Add(cellParamName);

                DataGridViewComboBoxCell cellSrcFields = new DataGridViewComboBoxCell();

                PropertyInfo[] srcProps = EntityTypeUtil.GetProperties(rule.SrcEntityType);
                if (srcProps != null && srcProps.Length > 0)
                {
                    foreach (PropertyInfo prop in srcProps)
                    {
                        cellSrcFields.Items.Add(prop.Name);
                    }
                    if(rule.SqlParameters !=null &&  
                        rule.SqlParameters.ContainsKey(paramName))
                    {
                        cellSrcFields.Value = rule.SqlParameters[paramName];
                    }
                }
                dr.Cells.Add(cellSrcFields);

                DataGridViewComboBoxCell cellDataType = new DataGridViewComboBoxCell();
                foreach (SqlDbType dbType in Enum.GetValues(typeof(SqlDbType)))
                {
                    cellDataType.Items.Add(dbType.ToString());
                }
                if(rule.ParameterTypes!=null && 
                    rule.ParameterTypes.ContainsKey(paramName))
                {
                    cellDataType.Value = rule.ParameterTypes[paramName].ToString();
                }
                dr.Cells.Add(cellDataType);
                
                this.dvSqlParameterBindings.Rows.Add(dr);

                paramMatch = paramMatch.NextMatch();
            }
        }

        #region Implementation of IWizardPageBase

        public event OnBeforeMoveToNext BeforeMoveToNext;
        public event OnBeforeDisplay BeforeDisplay;
        private IWizardPageBase _PrevPage;
        public IWizardPageBase PrevPage
        {
            get
            {
                return _PrevPage;
            }
            set
            {
                _PrevPage = value;
            }
        }

        private IWizardPageBase _NextPage;
        public IWizardPageBase NextPage
        {
            get
            {
                return _NextPage;
            }
            set
            {
                _NextPage = value;
            }
        }

        private string _Title = "Sql Parameters";
        public string Title
        {
            get
            {
                return _Title;
            }
            set
            {
                _Title = value;
            }
        }

        private string _Desc = "Specify how sql parameters should bind to source entity fields";
        public string Description
        {
            get
            {
                return _Desc;
            }
            set
            {
                _Desc = value;
            }
        }

        public void Init(Wizard owner)
        {
            this._Owner = owner;
        }

        public bool MoveNextPage()
        {
            try
            {
                EntityRelationRule rule =
                    (EntityRelationRule) this._Owner.SharedVariables["LinkRule"];
                rule.SqlParameters=new Dictionary<string, string>();
                rule.ParameterTypes=new Dictionary<string, SqlDbType>();

                foreach(DataGridViewRow dr in this.dvSqlParameterBindings.Rows)
                {
                    if (!dr.IsNewRow && dr.Cells[0].Value != null &&
                    dr.Cells[1].Value != null)
                    {
                        string paramName = dr.Cells[0].Value.ToString();
                        string propName = dr.Cells[1].Value.ToString();
                        rule.SqlParameters.Add(paramName, propName);

                        SqlDbType dbType = SqlDbType.VarChar;
                        if (dr.Cells[2].Value != null)
                        {
                            dbType = (SqlDbType)Enum.Parse(
                                                     typeof(SqlDbType),
                                                     dr.Cells[2].Value.ToString());
                        }
                        rule.ParameterTypes.Add(paramName, dbType);
                    }
                }

                if(this.BeforeMoveToNext!=null)
                    this.BeforeMoveToNext(new WizardPageNavigationEventArgs(this._Owner,false));

                return true;
            }
            catch(Exception ex)
            {
                ExceptionHandler.HandlesException(ex);
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public void MovePrevPage()
        {
            throw new System.NotImplementedException();
        }

        #endregion

       
    }
}
